package cn.snow.boot.aspect;

import cn.snow.boot.annotation.TargetDataSource;
import cn.snow.boot.datasource.DatasourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * ATTENTION:
 *   1. 保证在@Transactional之前执行，@Order需要设置顺序为负
 *   2. 使用注解切片时，需要同时使用@Aspect和@Component，前者保证切片，后者保证初始化到Spring容器中
 *
 * @author liuwanxiang
 * @version 2019/05/28
 */
@Slf4j
@Aspect
@Order(-1)
@Component
public class DynamicDataSourceAspect {
    @Around("@annotation(targetDataSource)")
    public Object proceed(ProceedingJoinPoint proceedingJoinPoint, TargetDataSource targetDataSource) throws Throwable {
        try {
            log.info("set database connection to {} only",targetDataSource.value());
            DatasourceContextHolder.setDatabase(targetDataSource.value());
            return proceedingJoinPoint.proceed();
        } finally {
            DatasourceContextHolder.clearDatabase();
            log.info("restore database connection");
        }
    }

}
